<template>
    <Modal :title="modalTitle" v-model="modalVisible" :mask-closable='false' :width="650" :styles="{top: '30px'}">
        <Form ref="userForm" :model="userForm" :label-width="70" :rules="userFormValidate">
            <FormItem label="登录名" prop="userName">
                <Input v-model="userForm.userName" autocomplete="off"/>
            </FormItem>
            <!--<FormItem label="手机号" prop="mobile">
                <Input v-model="userForm.mobile" type="number"/>
            </FormItem>-->
            <FormItem label="登录密码" prop="password" v-if="modalType===0" :error="errorPass">
                <Input type="password" v-model="userForm.password" autocomplete="off"/>
            </FormItem>
            <FormItem label="邮箱" prop="email">
                <Input v-model="userForm.email"/>
            </FormItem>
            <FormItem label="性别" prop="sex">
                <RadioGroup v-model="userForm.sex">
                    <Radio :label="2">男</Radio>
                    <Radio :label="1">女</Radio>
                </RadioGroup>
            </FormItem>
            <Form-item label="头像" prop="avatar">
                <upload-input :fileUrl="userForm.avatar" fileSize="200" fileWh="200*200" @on-change="handleUpload" width="400px" ref="upload"></upload-input>
            </Form-item>
           <!-- <Form-item label="所属部门" prop="deptName">
                <Poptip trigger="click" placement="right" title="选择部门" width="250">
                    <div style="display:flex;">
                        <Input v-model="userForm.deptName" readonly style="margin-right:10px;"/>
                        <Button icon="md-trash" @click="clearSelectDep">清空已选</Button>
                    </div>
                    <div slot="content">
                        <Tree :data="dataDep" :load-data="loadDataTree" @on-select-change="selectTree"></Tree>
                        <Spin size="large" fix v-if="deptLoading"></Spin>
                    </div>
                </Poptip>
            </Form-item>-->
            <!--<FormItem label="用户类型" prop="userType">
                <Select v-model="userForm.userType" placeholder="请选择">
                    <Option :value="'UT_USER'">普通用户</Option>
                    <Option :value="'UT_SYS'">管理员</Option>
                </Select>
            </FormItem>-->
            <FormItem label="角色分配" prop="roleIds">
                <Select v-model="userForm.roleIds" multiple>
                    <Option v-for="item in roleList" :value="item.id" :key="item.id" :label="item.roleName">
                        <!-- <div style="display:flex;flex-direction:column"> -->
                        <span style="margin-right:10px;">{{ item.roleName }}</span>
                        <span style="color:#ccc;">{{ item.remark }}</span>
                        <!-- </div> -->
                    </Option>
                </Select>
            </FormItem>
        </Form>
        <div slot="footer">
            <Button type="text" @click="cancelUser">取消</Button>
            <Button type="primary" :loading="submitLoading" @click="submitUser">提交</Button>
        </div>
    </Modal>
</template>

<script>
    import {addUser, editUser,getUser,loadDepartment, initDepartment,selertRoleList} from "@/api/index";
    import uploadInput from "@/views/my-components/flyme/upload-input";
    export default {
        name: "userAdd",
        components: {
            uploadInput
        },
        data() {
            const validatePassword = (rule, value, callback) => {
                if (value.length < 6) {
                    callback(new Error("密码长度不得小于6位"));
                } else {
                    callback();
                }
            };
            /*const validateMobile = (rule, value, callback) => {
                var reg = /^[1][3,4,5,6,7,8][0-9]{9}$/;
                if (!reg.test(value)) {
                    callback(new Error("手机号格式错误"));
                } else {
                    callback();
                }
            };*/
            return {
                accessToken: {},
                modalType: 0,
                errorPass: "",
                deptLoading: false,
                modalTitle: "",
                dataDep: [],
                userRoles: [],
                roleList: [],
                submitLoading: false,
                modalVisible: false,
                userForm: {
                    userName:"",
                    sex: 1,
                    password:"",
                    email:"",
                    mobile:"",
                    userType: 'UT_SYS',
                    avatar: "https://s1.ax1x.com/2018/05/19/CcdVQP.png",
                    roleIds: []
                },
                userFormValidate: {
                    userName: [
                        {required: true, message: "账号不能为空", trigger: "blur"}
                    ],
                    roleIds: [
                        {required: true, type: 'array',message: "角色不能为空", trigger: "change"}
                    ],
                    /*mobile: [
                        {required: true, message: "手机号不能为空", trigger: "blur"},
                        {validator: validateMobile, trigger: "blur"}
                    ],*/
                    password: [
                        {required: true, message: "密码不能为空", trigger: "blur"},
                        {validator: validatePassword, trigger: "blur"}
                    ]
                }
            }
        },
        methods: {
            init() {
                this.getParentList();
            },
            //添加-部门选择初始化
            getParentList() {
                initDepartment().then(res => {
                    if (res.status === true) {
                        this.dataDep = res.data;
                    }
                });
            },
            getRoleList() {
                selertRoleList().then(res => {
                    if (res.status === true) {
                        this.roleList = res.data;
                    }
                });
            },
            add() {
                this.modalType = 0;
                this.modalTitle='添加用戶';
                this.$refs.userForm.resetFields();
                this.modalVisible = true;
            },
            edit(id) {
                this.modalType = 1;
                this.getData(id);
                this.modalTitle='编辑用戶';


            },
            getData(id) {
                this.loading = true;
                this.modalVisible = true;
                getUser(id).then(res => {
                    this.loading = false;
                    if (res.status === true) {
                        this.userForm = res.data;
                    }
                });
            },
            cancelUser() {
                this.modalVisible = false;
            },
            viewPic() {
                this.viewImage = true;
            },
            clearSelectDep() {
                this.userForm.departmentId = "";
                this.userForm.deptName = "";
            },
            handleUpload(v) {
                this.userForm.avatar = v.fileUrl;
            },
            selectTree(v) {
                if (v.length > 0) {
                    // 转换null为""
                    for (let attr in v[0]) {
                        if (v[0][attr] === null) {
                            v[0][attr] = "";
                        }
                    }
                    let data = JSON.parse(JSON.stringify(v[0]));
                    this.userForm.departmentId = data.value;
                    this.userForm.deptName = data.label;
                }
            },
            submitUser() {
                this.$refs.userForm.validate(valid => {
                    if (valid) {
                        if (this.modalType === 0) {
                            // 添加用户 避免编辑后传入id
                            delete this.userForm.id;
                            delete this.userForm.status;
                            if (
                                this.userForm.password == "" ||
                                this.userForm.password == undefined
                            ) {
                                this.errorPass = "密码不能为空";
                                return;
                            }
                            if (this.userForm.password.length < 6) {
                                this.errorPass = "密码长度不得少于6位";
                                return;
                            }
                            this.submitLoading = true;
                            addUser(this.userForm).then(res => {
                                this.submitLoading = false;
                                if (res.status === true) {
                                    this.$Message.success("添加成功");
                                    this.$parent.refreshTable();
                                    this.modalVisible = false;
                                }
                            });
                        } else {
                            // 编辑
                            editUser(this.userForm).then(res => {
                                this.submitLoading = false;
                                if (res.status === true) {
                                    this.$Message.success("修改成功");
                                    this.$parent.refreshTable();
                                    this.modalVisible = false;
                                }
                            });
                        }
                    }
                });
            },
            loadDataTree(item, callback) {
                loadDepartment(item.value).then(res => {
                    if (res.status === true) {
                        callback(res.data);
                    }
                });
            }
        },
        mounted() {
            this.init();
            this.getRoleList();
        }
    }
</script>

<style>

</style>